package com.java.payweb.controller;

import com.java.payweb.service.CallbackService;
import com.java.payweb.unionpay.acp.sdk.AcpService;
import com.java.payweb.unionpay.acp.sdk.LogUtil;
import com.java.payweb.unionpay.acp.sdk.SDKConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author jiangli
 * @since 2019/12/16 21:53
 * http://jiangli.free.idcfengye.com/pay/callback/sync
 */
@RequestMapping("/pay/callback")
@Controller
public class UnPayCallbackController {
	@Autowired
	private CallbackService callbackService;

	private static final String PAY_SUCCESS = "pay_success";
	private static final String PAY_FAIL = "pay_fail";

	/**
	 * 同步回调
	 */
	@RequestMapping("/sync")
	public String sync(HttpServletRequest request) {
		Map<String, String> synResultMap = callbackService.sync(request);

		String encoding = request.getParameter(SDKConstants.param_encoding);
		if (!AcpService.validate(synResultMap, encoding)) {
			LogUtil.writeLog("验证签名结果[失败].");
			return PAY_FAIL;
		}
		request.setAttribute("txnAmt", Double.parseDouble(synResultMap.get("txnAmt")) / 100);
		request.setAttribute("orderId", Long.parseLong(synResultMap.get("orderId")));
		LogUtil.writeLog("验证签名结果[成功].");
		return PAY_SUCCESS;

	}

	/**
	 * 异步回调
	 */
	@RequestMapping("/async")
	public String async(HttpServletRequest request) {
		return callbackService.async(request);
	}
}
